package com.sardine.base.hbase.session.defaults;

import com.sardine.base.hbase.HBaseConfiguration;
import com.sardine.base.hbase.executor.DefaultHBaseExecutor;
import com.sardine.base.hbase.executor.DefaultHBaseRepository;
import com.sardine.base.hbase.executor.HBaseRepository;
import com.sardine.base.hbase.persister.DefaultHEntityAdhesive;
import com.sardine.base.hbase.persister.HEntityAdhesive;
import com.sardine.base.hbase.session.HBaseSession;
import com.sardine.base.hbase.session.HBaseSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/11/21
 * Time:10:05
 *
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class DefaultHBaseSessionFactory implements HBaseSessionFactory {
    private static final Logger logger = LoggerFactory.getLogger(DefaultHBaseSessionFactory.class);
    /**
     * hbase的配置中心
     */
    private HBaseConfiguration configuration;

    public DefaultHBaseSessionFactory(HBaseConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public HBaseSession getHSession() {
        return openHBaseConnection(configuration);
    }

    @Override
    public HBaseConfiguration getConfiguration() {
        return configuration;
    }

    private HBaseSession openHBaseConnection(HBaseConfiguration configuration) {
        try {
            HBaseConnectionManager hBaseConnectionManager = getHBaseConnectionManager(configuration);
            HEntityAdhesive persister = new DefaultHEntityAdhesive(configuration.getConfg());
            HBaseRepository repository = new DefaultHBaseRepository(hBaseConnectionManager.getConnection());
            DefaultHBaseExecutor executor = new DefaultHBaseExecutor(persister, repository);
            return new DefaultHBaseSession(configuration, executor);
        } catch (Exception e) {
            throw new RuntimeException("Error opening session.  Cause: " + e, e);
        }
    }

    private HBaseConnectionManager getHBaseConnectionManager(HBaseConfiguration configuration) {
        return new HBaseConnectionManager(configuration);
    }
}
